<?php
/**
 * 公共控制器
 */

namespace app\common\controller;
use think\Controller;

class OpenBase extends Controller {
	protected $stream_server = '';
	protected $header = [];
	protected $data = [];
	public $auth = false;
	public function __construct() {
		//获取返回的类型  默认html
		$param = IS_GET ? $_GET : $_POST;
		$param && $this->data = $param;
		$_GET = $_POST = $this->data;
		$GLOBALS['format'] = $this->format ? $this->format : 'json';
		$this->_initialize();

	}
	public function __get($name) {
		return $this->data[$name];
	}
	public function __set($name, $value) {
		$this->data[$name] = $value;
	}

	/**
	 * @name 初始化
	 */
	protected function _initialize() {
		$this->header = [
			'AuthAppid' => $_SERVER['HTTP_AUTH_APPID'],
			'AuthToken' => $_SERVER['HTTP_AUTH_TOKEN'],
			'AuthBasetime' => $_SERVER['HTTP_AUTH_BASETIME'],
		];
	}
	/**
	 * @name 调用服务发送请求操作
	 * @param string $type 请求的类型   [post,put,get,delete]
	 * @param array $params 请求时携带的参数
	 * @param string $url  请求的url
	 * @return array 请求后的返回数据
	 */
	protected function request($type = '', $params = [], $url = '') {
		if (!$type || !$url) {
			return [];
		}

		//加载httpful
		vendor('Bootstrap', VENDOR_PATH . 'Httpful' . DS);
		//初始化
		\Httpful\Bootstrap::init();
		//参数拼接
		if (in_array($type, ['get', 'delete'])) {
			$url .= '?' . http_build_query($params);
			$send = \Httpful\Request::$type($url);
		} else {
			$send = \Httpful\Request::$type($url)
				->sendsForm()
				->body($params);
		}
		foreach ($this->header as $key => $val) {
			$send = $send->$key($val);
		}
		$response = $send
			->expectsHtml()
			->send();
		//数据转换为数组返回
		return object2array($response->body);
	}
	/**
	 * @name 检测权限
	 */
	public function checkAuth() {
		$info = self::request('POST', [], 'http://live.shante.me/open/Service/getStreamServerUrl');
		$info = json_decode($info, true);
		if ($info['code'] != '10200') {
			$this->error = $info;
			$this->auth = false;
			return false;
		} else {
		    $this->stream_server = stristr($info['data']['service_host'],'/api',true);
			//$this->stream_server = $info['data']['service_host'];
		}
        
		if (str_replace(['http://', 'https://'], '', $this->stream_server) !== $_SERVER['SERVER_NAME']) {
			$this->error = ['code' => '10500', 'message' => 'Your server is not accessible'];
			$this->auth = false;
			return false;
		}
		$this->auth = true;
		return true;
	}
	protected function getError() {
		return $this->error;
	}
}
